'use client';

import { useState } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import {
  Copy,
  Check,
  Play,
  Code,
  FileText,
  Zap,
  TrendingUp,
  Shield,
  Database,
} from 'lucide-react';
import { cn } from '@/lib/utils';

/**
 * 代码示例组件
 * 支持仓颉语言语法高亮和复制功能
 */
export function CodeExample() {
  const [activeExample, setActiveExample] = useState('basic');
  const [copiedCode, setCopiedCode] = useState<string | null>(null);

  // 代码示例数据
  const examples = [
    {
      id: 'basic',
      title: '基础Actor定义',
      description: '创建一个简单的Actor并处理消息',
      icon: Code,
      category: '入门',
      code: `// 定义消息类型
struct GreetingMessage {
    name: String
    reply: ActorRef<String>
}

// 定义Actor行为
class GreetingActor <: Actor {
    func receive(message: GreetingMessage): Unit {
        let greeting = "Hello, \(message.name)!"
        message.reply.tell(greeting)
    }
}

// 创建Actor系统
let system = ActorSystem("greeting-system")
let greeter = system.actorOf<GreetingActor>("greeter")

// 发送消息
let reply = system.actorOf<ReplyActor>("reply")
greeter.tell(GreetingMessage("CActor", reply))`,
    },
    {
      id: 'financial',
      title: '高频交易Actor',
      description: '金融场景下的高性能交易处理',
      icon: TrendingUp,
      category: '金融',
      code: `// 交易消息定义
struct TradeOrder {
    symbol: String
    quantity: Int64
    price: Decimal
    side: TradeSide
    timestamp: Int64
}

// 高频交易Actor
class HighFrequencyTrader <: Actor {
    var positions: HashMap<String, Int64> = HashMap()
    var riskLimits: HashMap<String, Decimal> = HashMap()
    
    func receive(order: TradeOrder): Unit {
        // 毫秒级风险检查
        if (checkRiskLimits(order)) {
            // 执行交易
            executeOrder(order)
            // 更新持仓
            updatePosition(order)
            // 发送确认
            sender().tell(OrderConfirmation(order.id, "FILLED"))
        } else {
            sender().tell(OrderRejection(order.id, "RISK_LIMIT_EXCEEDED"))
        }
    }
    
    func checkRiskLimits(order: TradeOrder): Bool {
        let currentPosition = positions.getOrElse(order.symbol, 0)
        let newPosition = currentPosition + order.quantity
        let limit = riskLimits.getOrElse(order.symbol, Decimal(1000000))
        return abs(newPosition * order.price) <= limit
    }
}`,
    },
    {
      id: 'payment',
      title: '支付处理系统',
      description: '实时支付处理和状态管理',
      icon: Shield,
      category: '支付',
      code: `// 支付状态机Actor
class PaymentProcessor <: Actor {
    var state: PaymentState = PaymentState.PENDING
    var retryCount: Int32 = 0
    let maxRetries: Int32 = 3
    
    func receive(message: PaymentMessage): Unit {
        match (message, state) {
        case (ProcessPayment(amount, account), PENDING) =>
            processPayment(amount, account)
            
        case (PaymentSuccess(txId), PROCESSING) =>
            state = PaymentState.COMPLETED
            notifySuccess(txId)
            
        case (PaymentFailure(error), PROCESSING) =>
            if (retryCount < maxRetries) {
                retryCount += 1
                scheduleRetry()
            } else {
                state = PaymentState.FAILED
                notifyFailure(error)
            }
            
        case _ =>
            // 忽略无效状态转换
        }
    }
    
    func processPayment(amount: Decimal, account: String): Unit {
        state = PaymentState.PROCESSING
        // 异步调用支付网关
        paymentGateway.processAsync(amount, account)
            .onComplete { result =>
                match result {
                case Success(txId) => self.tell(PaymentSuccess(txId))
                case Failure(error) => self.tell(PaymentFailure(error))
                }
            }
    }
}`,
    },
    {
      id: 'ledger',
      title: '分布式账本',
      description: '基于事件溯源的账本系统',
      icon: Database,
      category: '账本',
      code: `// 账本事件定义
interface LedgerEvent {
    let timestamp: Int64
    let eventId: String
}

struct AccountCreated <: LedgerEvent {
    let accountId: String
    let initialBalance: Decimal
}

struct TransactionExecuted <: LedgerEvent {
    let fromAccount: String
    let toAccount: String
    let amount: Decimal
    let transactionId: String
}

// 分布式账本Actor
class DistributedLedger <: PersistentActor {
    var accounts: HashMap<String, Decimal> = HashMap()
    var eventStore: EventStore = EventStore()
    
    func receiveCommand(cmd: LedgerCommand): Unit {
        match cmd {
        case CreateAccount(accountId, initialBalance) =>
            if (!accounts.containsKey(accountId)) {
                let event = AccountCreated(accountId, initialBalance)
                persist(event) { evt =>
                    applyEvent(evt)
                    sender().tell(AccountCreatedConfirmation(accountId))
                }
            }
            
        case Transfer(from, to, amount) =>
            if (canTransfer(from, to, amount)) {
                let event = TransactionExecuted(from, to, amount, generateTxId())
                persist(event) { evt =>
                    applyEvent(evt)
                    sender().tell(TransferConfirmation(evt.transactionId))
                }
            } else {
                sender().tell(TransferRejection("INSUFFICIENT_FUNDS"))
            }
        }
    }
    
    func applyEvent(event: LedgerEvent): Unit {
        match event {
        case AccountCreated(accountId, balance) =>
            accounts[accountId] = balance
            
        case TransactionExecuted(from, to, amount, _) =>
            accounts[from] = accounts[from] - amount
            accounts[to] = accounts.getOrElse(to, Decimal(0)) + amount
        }
    }
}`,
    },
  ];

  /**
   * 复制代码到剪贴板
   */
  const copyCode = async (code: string, exampleId: string) => {
    try {
      await navigator.clipboard.writeText(code);
      setCopiedCode(exampleId);
      setTimeout(() => setCopiedCode(null), 2000);
    } catch (err) {
      console.error('Failed to copy code:', err);
    }
  };

  /**
   * 代码高亮处理函数
   * @param code - 原始代码字符串
   * @returns 原始代码字符串（不进行HTML标签处理）
   */
  const highlightCode = (code: string) => {
    return code;
  };

  const activeExampleData = examples.find(ex => ex.id === activeExample);

  return (
    <section className="py-16 bg-gradient-to-b from-background to-muted/20">
      <div className="container">
        <div className="text-center mb-12">
          <h2 className="text-3xl font-bold mb-4">仓颉语言代码示例</h2>
          <p className="text-lg text-muted-foreground">
            探索CActor在不同场景下的实际应用代码
          </p>
        </div>

        <div className="grid grid-cols-1 lg:grid-cols-4 gap-8 max-w-7xl mx-auto">
          {/* 示例选择器 */}
          <div className="lg:col-span-1">
            <div className="space-y-3">
              {examples.map(example => {
                const Icon = example.icon;
                const isActive = activeExample === example.id;

                return (
                  <Card
                    key={example.id}
                    className={cn(
                      'cursor-pointer transition-all duration-200 hover:shadow-md',
                      isActive && 'ring-2 ring-primary bg-primary/5'
                    )}
                    onClick={() => setActiveExample(example.id)}
                  >
                    <CardContent className="p-4">
                      <div className="flex items-start space-x-3">
                        <div className="p-2 rounded-lg bg-muted">
                          <Icon className="h-4 w-4" />
                        </div>
                        <div className="flex-1 min-w-0">
                          <div className="flex items-center space-x-2 mb-1">
                            <h3 className="text-sm font-semibold truncate">
                              {example.title}
                            </h3>
                            <Badge variant="outline" className="text-xs">
                              {example.category}
                            </Badge>
                          </div>
                          <p className="text-xs text-muted-foreground line-clamp-2">
                            {example.description}
                          </p>
                        </div>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          </div>

          {/* 代码展示区域 */}
          <div className="lg:col-span-3">
            {activeExampleData && (
              <Card className="h-full">
                <CardHeader>
                  <div className="flex items-center justify-between">
                    <div className="flex items-center space-x-3">
                      <div className="p-2 rounded-lg bg-primary/10">
                        <activeExampleData.icon className="h-5 w-5 text-primary" />
                      </div>
                      <div>
                        <CardTitle className="text-xl">
                          {activeExampleData.title}
                        </CardTitle>
                        <p className="text-sm text-muted-foreground mt-1">
                          {activeExampleData.description}
                        </p>
                      </div>
                    </div>
                    <div className="flex items-center space-x-2">
                      <Badge variant="secondary">
                        {activeExampleData.category}
                      </Badge>
                      <Button
                        size="sm"
                        variant="outline"
                        onClick={() =>
                          copyCode(activeExampleData.code, activeExampleData.id)
                        }
                      >
                        {copiedCode === activeExampleData.id ? (
                          <>
                            <Check className="mr-2 h-4 w-4 text-green-600" />
                            已复制
                          </>
                        ) : (
                          <>
                            <Copy className="mr-2 h-4 w-4" />
                            复制代码
                          </>
                        )}
                      </Button>
                    </div>
                  </div>
                </CardHeader>
                <CardContent>
                  <div className="relative">
                    <pre className="bg-muted/50 rounded-lg p-6 overflow-x-auto text-sm leading-relaxed">
                      <code
                        className="language-cangjie"
                        dangerouslySetInnerHTML={{
                          __html: highlightCode(activeExampleData.code),
                        }}
                      />
                    </pre>

                    {/* 代码行数 */}
                    <div className="absolute left-2 top-6 text-xs text-muted-foreground/50 select-none">
                      {activeExampleData.code.split('\n').map((_, index) => (
                        <div key={index} className="leading-relaxed">
                          {index + 1}
                        </div>
                      ))}
                    </div>
                  </div>

                  {/* 代码说明 */}
                  <div className="mt-6 p-4 rounded-lg bg-muted/30">
                    <h4 className="text-sm font-medium mb-2 flex items-center">
                      <FileText className="mr-2 h-4 w-4" />
                      代码说明
                    </h4>
                    <p className="text-sm text-muted-foreground">
                      {getCodeExplanation(activeExampleData.id)}
                    </p>
                  </div>

                  {/* 运行按钮 */}
                  <div className="mt-4 flex justify-center">
                    <Button className="w-full sm:w-auto">
                      <Play className="mr-2 h-4 w-4" />
                      在线运行示例
                    </Button>
                  </div>
                </CardContent>
              </Card>
            )}
          </div>
        </div>

        {/* 特性说明 */}
        <div className="mt-16 grid grid-cols-1 md:grid-cols-3 gap-6">
          <Card className="text-center p-6">
            <Zap className="h-8 w-8 mx-auto mb-3 text-blue-600" />
            <h3 className="font-semibold mb-2">高性能</h3>
            <p className="text-sm text-muted-foreground">
              仓颉语言的原生性能优势，配合CActor优化
            </p>
          </Card>

          <Card className="text-center p-6">
            <Shield className="h-8 w-8 mx-auto mb-3 text-green-600" />
            <h3 className="font-semibold mb-2">类型安全</h3>
            <p className="text-sm text-muted-foreground">
              强类型系统确保代码的可靠性和安全性
            </p>
          </Card>

          <Card className="text-center p-6">
            <Code className="h-8 w-8 mx-auto mb-3 text-purple-600" />
            <h3 className="font-semibold mb-2">简洁语法</h3>
            <p className="text-sm text-muted-foreground">
              现代化的语法设计，提高开发效率
            </p>
          </Card>
        </div>
      </div>
    </section>
  );
}

/**
 * 获取代码说明
 */
function getCodeExplanation(exampleId: string): string {
  const explanations = {
    basic:
      '这个示例展示了CActor的基本用法：定义消息类型、创建Actor类、处理消息和发送响应。Actor系统提供了类型安全的消息传递机制。',
    financial:
      '高频交易场景需要极低的延迟和高吞吐量。这个示例展示了如何实现毫秒级的风险检查、持仓管理和订单执行，满足金融交易的严格要求。',
    payment:
      '支付处理系统使用状态机模式来管理支付流程。支持重试机制、异步处理和状态转换，确保支付的可靠性和一致性。',
    ledger:
      '分布式账本使用事件溯源模式，所有状态变更都通过事件记录。这确保了数据的完整性、可审计性和分布式一致性。',
  };

  return explanations[exampleId as keyof typeof explanations] || '';
}
